<template>
  <div class="permission-container">
    <div class="app-container">
      <!-- 表格 -->
      <el-card>
        <div style="text-align: right; margin-bottom: 20px">
          <el-button type="primary" size="small" @click="addPermission('0', 1)">添加权限</el-button>
        </div>

        <el-table v-loading="loading" border :data="PermissionList" row-key="id">
          <el-table-column label="名称" prop="name" />
          <el-table-column label="标识" prop="code" />
          <el-table-column label="描述" prop="description" />
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-button v-if="row.type === 1" type="text" @click="addPermission(row.id, 2)">
                添加
              </el-button>
              <el-button type="text" @click="editPermission(row.id)">编辑</el-button>
              <el-button type="text" @click="delPermission(row.id, $index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 添加权限弹窗 -->
    <per-dialog ref="perDialog" @addPermissionEv="addPerFn" @editPermissionEv="editPermissionFn" />
  </div>
</template>

<script>
import {
  getPermissionListAPI,
  addPermissionAPI,
  getPermissionDetailAPI,
  updatePermissionAPI,
  delPermissionAPI
} from '@/api'
import { transTree } from '@/utils'
import perDialog from './components/perDialog.vue'
export default {
  components: {
    'per-dialog': perDialog
  },
  data() {
    return {
      // 权限列表(树形结构)
      PermissionList: [],
      loading: true
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionListAPI()
      console.log(res)
      this.PermissionList = transTree(res.data, '0')
      this.loading = false
    },

    // 添加权限按钮
    addPermission(pid, type) {
      this.$refs.perDialog.formData.pid = pid
      this.$refs.perDialog.formData.type = type
      this.$refs.perDialog.isEdit = false
      this.$refs.perDialog.showDialog = true
    },

    // 添加权限功能
    async addPerFn(obj) {
      await addPermissionAPI(obj)
      // 刷新页面
      this.getPermissionList()
    },

    // 编辑权限按钮
    editPermission(id) {
      this.$refs.perDialog.isEdit = true
      this.$refs.perDialog.showDialog = true
      // eslint-disable-next-line
      this.$nextTick(async () => {
        const res = await getPermissionDetailAPI(id)
        console.log(res)
        this.$refs.perDialog.formData = res.data
      })
    },

    // 编辑权限功能
    async editPermissionFn(data) {
      await updatePermissionAPI(data)
      // 刷新页面
      this.getPermissionList()
    },

    // 删除权限点
    async delPermission(id, index) {
      await delPermissionAPI(id)
      console.log(index)
      // 刷新页面
      this.getPermissionList()
    }
  }
}
</script>

<style lang="scss" scoped></style>
